<?php

namespace App\Services;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use App\Exceptions\FireFlyException;

class AliPayService
{
    // 发起支付
    public static function h5Pay($order_sn,$title,$money,$notifyUrl,$quitUrl,$returnUrl)
    {
        //1. 设置参数（全局只需设置一次）
        Factory::setOptions(self::getOptions($notifyUrl));
        //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
        // quit_url 用户付款中途退出返回商户网站的地址。  return_url
        $result = Factory::payment()->wap()->pay($title, $order_sn, (int) ($money * 100), $quitUrl,$returnUrl);
        $responseChecker = new ResponseChecker();
        //3. 处理响应或异常
        if ($responseChecker->success($result)) {
            return $result->body;
        } else {
            throw new FireFlyException(403,"支付宝下单失败，".$result->msg . "，" . $result->subMsg);
        }
    }
    private static function getOptions($notifyUrl)
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = config('alipay.appId');
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = config('alipay.merchantPrivateKey');
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        $options->alipayPublicKey = config('alipay.alipayPublicKey');
        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = $notifyUrl;
        return $options;
    }
}
